package com.hbu.fleastreet.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 用于将图片保存到对应位置。形如img/product/xxx.jpg
 * img/product/100001.jpg
 *
 */
public class FileUtil {

	/**
	 * 保存上传的文件
	 *
	 * @param images
	 * @throws Exception
	 */
	public static void saveFile(MultipartFile images, Integer productId) throws Exception {

			if (images == null || images.isEmpty())
				return;
			File target = new File(com.hbu.fleastreet.common.Constant.PREFIX_URL_SAVE_IMAGE);
			if (!target.isDirectory()) {
				target.mkdirs();
			}
		 	String originalFilename = images.getOriginalFilename();
			String fileName = productId+"." + getPostfix(originalFilename);
			//        MessageDigest md = MessageDigest.getInstance("MD5");
			//        md.update(file.getBytes());
			//        String fileName = (Helper.bytesToHex(md.digest(),0,md.digest().length-1)) + "." + getPostfix(originalFilename);
			File file1 = new File(target.getPath() + "/" + fileName);
			Files.write(Paths.get(file1.toURI()), images.getBytes(), StandardOpenOption.CREATE);


	}

	/**
	 * 获得文件的后缀名
	 * @param fileName
	 * @return
	 */
	public static String getPostfix(String fileName) {
		if (fileName == null || "".equals(fileName.trim())) {
			return "";
		}
		if (fileName.contains(".")) {
			return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		}
		return "";
	}

}
